"""
Stripe管理层
负责协调客户、产品、订阅服务的交互
"""

import stripe
import uuid
import logging
from datetime import datetime
from typing import Dict, Any, Optional
from fastapi import HTTPException

from services.customer_service import CustomerService
from services.product_service import ProductService
from services.subscription_service import SubscriptionService
from services.webhook_service import WebhookService
from utils.config import Config
from utils.data_store import DataStore

logger = logging.getLogger(__name__)


class StripeManager:
    """Stripe管理层，协调各个服务的交互"""
    
    def __init__(self):
        # 初始化各个服务
        self.customer_service = CustomerService()
        self.product_service = ProductService()
        self.subscription_service = SubscriptionService(
            customer_service=self.customer_service,
            product_service=self.product_service
        )
        self.webhook_service = WebhookService(
            customer_service=self.customer_service,
            product_service=self.product_service,
            subscription_service=self.subscription_service
        )
    
    def get_system_status(self) -> Dict[str, Any]:
        """获取系统状态"""
        customers_count = len(self.customer_service.customers)
        products_count = len(self.product_service.products)
        subscriptions_count = len(self.subscription_service.subscriptions)
        
        return {
            "status": "running",
            "timestamp": datetime.now().isoformat(),
            "statistics": {
                "customers": customers_count,
                "products": products_count,
                "subscriptions": subscriptions_count
            },
            "data_files": {
                "customers": Config.CUSTOMERS_FILE,
                "products": Config.PRODUCTS_FILE,
                "subscriptions": Config.SUBSCRIPTIONS_FILE
            },
            "webhook": {
                "url": Config.WEBHOOK_URL,
                "supported_events": self.webhook_service.get_supported_events(),
                "handler_count": len(self.webhook_service.event_handlers)
            }
        }
    
    def handle_subscription_success(self, session_id: str) -> Dict[str, Any]:
        """处理订阅支付成功"""
        try:
            # 从Stripe获取会话详情
            session = stripe.checkout.Session.retrieve(session_id)
            
            # 如果会话完成，创建本地订阅记录
            if session.payment_status == 'paid' and session.subscription:
                # 从元数据中获取本地客户和产品ID
                customer_id = session.metadata.get('local_customer_id')
                product_id = session.metadata.get('local_product_id')
                
                if customer_id and product_id:
                    # 检查是否已有订阅记录
                    existing_subscription = None
                    for sub_id, sub_data in self.subscription_service.subscriptions.items():
                        if (sub_data['customer_id'] == customer_id and 
                            sub_data['product_id'] == product_id):
                            existing_subscription = sub_data
                            break
                    
                    if existing_subscription:
                        # 如果已存在订阅记录，更新状态而不是创建新的
                        existing_subscription['stripe_subscription_id'] = session.subscription
                        existing_subscription['status'] = 'active'
                        existing_subscription['updated_at'] = datetime.now().isoformat()
                        existing_subscription['metadata'] = session.metadata
                        
                        DataStore.save_data(Config.SUBSCRIPTIONS_FILE, self.subscription_service.subscriptions)
                        logger.info(f"订阅支付成功，更新现有记录: {existing_subscription['id']}")
                    else:
                        # 创建新的本地订阅记录
                        local_subscription_id = str(uuid.uuid4())
                        subscription_data = {
                            'id': local_subscription_id,
                            'stripe_subscription_id': session.subscription,
                            'customer_id': customer_id,
                            'product_id': product_id,
                            'status': 'active',
                            'cancel_at_period_end': False,
                            'metadata': session.metadata,
                            'created_at': datetime.now().isoformat(),
                            'updated_at': datetime.now().isoformat()
                        }
                        
                        # 保存到本地存储
                        self.subscription_service.subscriptions[local_subscription_id] = subscription_data
                        DataStore.save_data(Config.SUBSCRIPTIONS_FILE, self.subscription_service.subscriptions)
                        
                        logger.info(f"订阅支付成功，本地记录创建: {local_subscription_id}")
            
            return {
                "status": "success",
                "message": "订阅支付成功！",
                "session_id": session_id,
                "subscription_id": session.subscription,
                "timestamp": datetime.now().isoformat()
            }
            
        except stripe.error.StripeError as e:
            logger.error(f"获取会话信息失败: {str(e)}")
            return {
                "status": "error",
                "message": "获取支付信息失败",
                "session_id": session_id,
                "timestamp": datetime.now().isoformat()
            }
    
    def reload_all_data(self):
        """重新加载所有数据"""
        self.customer_service.reload_data()
        self.product_service.reload_data()
        self.subscription_service.reload_data()
        logger.info("所有数据重新加载完成")
    
    def backup_all_data(self) -> Dict[str, bool]:
        """备份所有数据"""
        results = {
            "customers": DataStore.backup_data(Config.CUSTOMERS_FILE),
            "products": DataStore.backup_data(Config.PRODUCTS_FILE),
            "subscriptions": DataStore.backup_data(Config.SUBSCRIPTIONS_FILE)
        }
        
        success_count = sum(results.values())
        logger.info(f"数据备份完成，成功备份 {success_count}/3 个文件")
        
        return results
